package com.xdf.docmanagementsystem.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @program: doc-management-system
 * @description: JWT工具类
 * @author: Zhang
 * @create: 2020-06-19 22:00
 **/
public class JWTUtil {
    private static String USER_ACCOUNT = "userAccount";
    private static int expireTime = 8 * 60 * 60 * 1000;

    /**
     * 创建JWT
     *
     * @param userName
     * @param secret
     * @return
     */
    public static String createJWT(String userName, String secret) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        Date createDate = new Date();
        Date expireDate = new Date(System.currentTimeMillis() + expireTime);
        return JWT.create()
                .withClaim(USER_ACCOUNT, userName)
                .withIssuedAt(createDate)
                .withExpiresAt(expireDate)
                .sign(algorithm);
    }

    /**
     * 检验JWT
     *
     * @param jwt
     * @param userName
     * @return
     */
    public static boolean verifyJWT(String jwt, String userName, String secret) {
        DecodedJWT decodedJWT = getDecodedJWT(jwt, userName, secret);
        if (decodedJWT == null)
            return false;
        return decodedJWT.getExpiresAt().getTime() > new Date().getTime();

    }


    public static DecodedJWT getDecodedJWT(String jwt, String userName, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier jwtVerifier = JWT.require(algorithm)
                    .withClaim(USER_ACCOUNT, userName)
                    .build();
            DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
            return decodedJWT;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取用户
     *
     * @param token
     * @return
     */
    public static String getUserNameFromToken(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim(USER_ACCOUNT).asString();
    }
}
